#!/bin/bash

# Description: 指定时间关电脑，关机前播放一首歌提示
# Author: zhouhui
# Release: 2015-03-21

[ $(lsof $0 |wc -l) -gt 2 ] && { echo "already running !" ; exit 0; }
sleep 20

#====== global variable =====
OFF_TIME='23:28'
PRE_ALM=30 
PLAY_LIST=$(cat "${0%/*}/playlist.lst" |sed '/^[[:blank:]]*$/d')
#[ -z "$PLAY_LIST" ] &&  echo "WARN: play list is empty." ; exit 89 ; }
PLAY_LIST="${PLAY_LIST:-/home/weaver/音乐/to be by your side.mp3}"

function fn_check_time()
{
    # current min of day 
    local cur=$[ $(date +%-M) + $(date +%k)*60 ] # timer min of day
    local timer=$[ $(date -d "${OFF_TIME}" +%H)*60 + $(date -d ${OFF_TIME} +%M)] 

    if  [[ "$OFF_TIME" =~ 0[0-2]: ]] 
    then
        echo "$[ 1440 - timer - cur ]"
    else
        echo "$[ timer - cur ]"
    fi

    return 0
}

function get_random_song()
{
    local play_list="$1"
    play_list=$(echo  "${play_list}" |sed 's/^[[:blank:]]*//; s/[[:blank:]]*$//')
    [ -z "${play_list}" ] &&  return 21

    local line_count=$(echo "${play_list}" |wc -l)
    local segment=$(echo "scale=2;32768/${line_count}" |bc)
    local  index=$(echo "scale=2;(${RANDOM}+1)/${segment}" |bc)

    echo "${play_list}" |sed -n "$[ ${index%.*} + 1 ]p"
    return 0
}

function fn_play_a_song()
{
    local action="$1"
    local song_path="$2"
    case "${action}" in 
        'play' ) 
            [ ! -f "${song_path}" ] && song_path=''
            audacious --headless --play "${song_path}" &>/dev/null &
        ;;
        'stop' )
             local pids=$(ps -eo pid,cmd |awk '/audacious/ && !/awk/{print $1}') 
             [ -n "${pids}" ] && kill ${pids}
        ;;
        *) echo "ERROR: unknown action(${action})."
    esac 
    return $?
}

function fn_main()
{
    while :
    do
        if [ $(fn_check_time) -le 5 -a $(fn_check_time) -ge 0 ]
        then
            /usr/bin/wall "$(echo -e "\e[41;37m Poweroff after 5 minutes later.\e[0m")"
            local song_path=$(get_random_song "${PLAY_LIST}")
            fn_play_a_song play "${song_path}"
            sleep 300 
            fn_play_a_song stop
            break 
        fi 
        sleep 10
    done
    
    sync; sync ; sync
    /usr/bin/wall "$(echo -e "\e[1;7;31m Poweroff after 20 seconds later. Execute command ting to stop.\e[0m")"
    sleep 20
    ~weaver/query_poweroff.py 
    
#    sudo /sbin/init 0
}
export PS4='+{$LINENO}'
set -x 
fn_main 2>/home/weaver/t.log
